﻿using BasicsClassLibrary.Tool.Configure;
using Kong;
using Kong.Models;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;
using Passport.Infrastructure;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace BasicsClassLibrary.Tool.Kong
{
    public static class RouteToKong
    {
		/// <summary>
		/// 路由注册到kong；
		/// </summary>
		/// <param name="services"></param>
		/// <returns></returns>
		public static IServiceCollection RouteRegistToKong(this IServiceCollection services)
		{
			if (!Convert.ToBoolean( AppHelper.ReadAppSettings("Kong", "Disable")))
			{
				var konghost = AppHelper.ReadAppSettings("Kong", "Host") ?? throw new ArgumentNullException("Kong:Host cannot be null or empty!");

				var options = new KongClientOptions(HttpClientFactory.Create(), konghost);
				var client = new KongClient(options);
				services.AddSingleton<KongClient>(client);
				
				var upStream = AppHelper.ReadAppSettingT<UpStream>("Kong", "Upstream"); 
				var target = AppHelper.ReadAppSettingT<TargetInfo>("Kong", "Target"); //负载均衡，健康检测使用

				if (upStream.Name != null && target.Tags != null)
				{
					upStream.Created_at = DateTime.Now;
					upStream = client.UpStream.UpdateOrCreate(upStream).Result;

					target.Target = $"{PassportConfig.GetHealthHost()}:{PassportConfig.GetCurrentPort()}";
					target.Id = PassportTools.GuidFromString($"{Dns.GetHostName()}{target.Target}");
					target.Created_at = DateTime.Now;
					target.UpStream = new TargetInfo.UpStreamId { Id = upStream.Id.Value };
					client.Target.Add(target).Wait();

					PassportConsole.Success($"[Kong]UpStream registered:{upStream.Name} Target:{target.Target}");

					// app.UseKongHealthChecks(upStream, onExecuter);
				}
				var kongServices = AppHelper.ReadAppSettings<ServiceInfo>("Kong", "Services");
				var kongRoutes = AppHelper.ReadAppSettings<RouteInfo>("Kong", "Routes"); 

				if (kongServices?.Count > 0 == true)
				{
					foreach (var item in kongServices)
					{
						item.Updated_at = DateTime.Now;
						item.Path = string.IsNullOrWhiteSpace(item.Path) ? null : item.Path;
						client.Service.UpdateOrCreate(item).Wait();
						PassportConsole.Success($"[Kong]Service registered:{item.Name}");
					}
				}

				if (kongRoutes?.Count > 0 == true)
				{
					foreach (var item in kongRoutes)
					{
						item.Updated_at = DateTime.Now;
						client.Route.UpdateOrCreate(item).Wait();
						PassportConsole.Success($"[Kong]Route registered:{item.Name}");
					}
				}
			}

			return services;
		}
	}
}
